package fnic.prehand.common;

import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.net.HttpURLConnection;
import java.net.URL;

import org.apache.log4j.Logger;

public class HttpMsgService {
	private static final String ENCODING = "utf-8";
	private static Logger LOG = Logger.getLogger(HttpMsgService.class);
	
	// singleton
	private static HttpMsgService instance = new HttpMsgService();

	public static HttpMsgService getInstance() {
		return instance;
	}
	/*
	 * 给管理节点发送POST请求 
	 * 
	 * 用途：
	 * 1、推送PC索引成功的索引ID等数据到管理节点，保存到数据库
	 * 2、推送Phone索引成功的索引ID、数据主观评价、经纬度等数据到管理节点，保存到数据库
	 */	
	public boolean sendPostMsg(boolean needRspContent, String headurl, String bodymsg, StringBuilder rspbuilder) {
		try {
			URL gatewayUrl = new URL(headurl);
			HttpURLConnection httpURLConnection = (HttpURLConnection) gatewayUrl.openConnection();

			// 设置连接属性 http head
			httpURLConnection.setRequestMethod("POST");
			httpURLConnection.setDoInput(true);
			httpURLConnection.setDoOutput(true);
			httpURLConnection.setUseCaches(false);
			httpURLConnection.setRequestProperty("Content-Length", ""+ bodymsg.getBytes(ENCODING).length);
			httpURLConnection.setRequestProperty("Content-Type", "application/json; charset=utf-8");

			// 建立输出流，并写入json数据
			OutputStream outputStream = httpURLConnection.getOutputStream();
			PrintWriter pw = new PrintWriter(outputStream, true);
			pw.println(bodymsg);
			pw.flush();
			pw.close();
			InputStream rspstream = httpURLConnection.getInputStream(); // 这一行必须要，否则消息发送不出去
			if(httpURLConnection.getResponseCode() != HttpURLConnection.HTTP_OK){
				LOG.error("sendPostMsg2ctrl rsp error, code:" + httpURLConnection.getResponseCode());
				return false;
			}
			
			//下面判断是否需要获取http响应内容
			if(needRspContent){
				BufferedReader bufferedReader = null;
				try {
					bufferedReader = new BufferedReader(new InputStreamReader(rspstream,"utf-8"));
					String tempString;
					while ((tempString = bufferedReader.readLine()) != null) {
						rspbuilder.append(tempString);
					}
					bufferedReader.close();
					rspstream.close();
				} catch (Exception e) {
					//向管理节点请求sessionKey校验失败 -- 获取响应内容失败
					LOG.error("get http Rsp stream fail: " + e.getMessage());
					return false;
				}
			}
			
		} catch (Exception e) {
			LOG.error("send POST Msg fail: "+e.getMessage()+ ", url:"+headurl);
			return false;
			//推送数据至管理节点失败--推送索引消息至管理节点失败
//			if(ptype == 1)	
//			{   
//				//LOG.info("index info add to pcQueue ...");
//				BlockQueueService.getInstance().addPcConnectQueueItem(msg);
//				//LOG.info("pcConnectQueue size ..." + ss.size());				
//			}
//			else if (ptype == 2) 
//			{	
//				//LOG.info("index info add to phoneQueue ...");
//				BlockQueueService.getInstance().addPhoneConnectQueueItem(msg);
//				//LOG.info("index info add to phoneQueue ..."+ss.size());
//			}
		}
		return true;
	}

	/*
	 * 发送Get方法给管理节点
	 *  用途：1、发送校验数据probeid+keysession到进行管理平台进行校验
	 */
	public boolean sendGetMsg(boolean needRspContent, String headurl, StringBuilder rspbuilder) {
		try {
			// 建立链接
			URL gatewayUrl = new URL(headurl);
			HttpURLConnection httpURLConnection = (HttpURLConnection) gatewayUrl.openConnection();

			// 设置连接属性 http head
			httpURLConnection.setRequestMethod("GET");
			httpURLConnection.setDoInput(true);
			httpURLConnection.setDoOutput(false);
			httpURLConnection.setUseCaches(false);
			httpURLConnection.setRequestProperty("Content-Type", "application/text; charset=utf-8");
			
			//不需要http body
			httpURLConnection.connect();
			InputStream rspstream = httpURLConnection.getInputStream();
			
			if(httpURLConnection.getResponseCode() != HttpURLConnection.HTTP_OK){
				LOG.error("sendGetMsg2ctrl rsp error, code:" + httpURLConnection.getResponseCode());
				return false;
			}
			
			//下面判断是否需要获取http响应内容
			if(needRspContent){
				BufferedReader bufferedReader = null;
				try {
					bufferedReader = new BufferedReader(new InputStreamReader(rspstream,"utf-8"));
					String tempString;
					while ((tempString = bufferedReader.readLine()) != null) {
						rspbuilder.append(tempString);
					}
					bufferedReader.close();
					rspstream.close();
				} catch (Exception e) {
					//向管理节点请求sessionKey校验失败 -- 获取响应内容失败
					LOG.error("get http Rsp stream fail: " + e.getMessage());
					return false;
				}
			}
		} catch (Exception e) {
			LOG.error("send GET Msg fail: "+e.getMessage()+ ", url:"+headurl);
			return false;
		}

		return true;
	}
	
}
